package com.xindaoapp.framework.view;


import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.util.LogUtils;
import com.squareup.picasso.Picasso;
import com.xindaoapp.framework.R;
import com.xindaoapp.framework.utils.CommonUtil;

public class RollViewPager extends ViewPager {

	public RollViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	private Context ct;
	private List<View> dotList;
	private int dotFocus;
	private int dotNormal;
	private TextView tvDescription;
	private float mLastMotionX;
	private float mLastMotionY;

	public interface OnPagerClickCallBack {
		public void pagerClickCallBack(int position);
	}

	public interface MyOnTouchCllickCallBack {
		public void OnTouchCllick(int position);
	}

	public MyOnTouchCllickCallBack onTouchCllickCallBack;
	private boolean wifi;

	public RollViewPager(Context ct, List<View> dotList, int dotFocus,
			int dotNormal, MyOnTouchCllickCallBack myOnTouchCllickCallBack) {
		super(ct);
		this.ct = ct;
		this.dotList = dotList;
		this.dotFocus = dotFocus;
		this.dotNormal = dotNormal;
		taskPager = new TaskPager();
		 this.onTouchCllickCallBack = myOnTouchCllickCallBack;
		 myOnTouchListener = new MyOnTouchListener();
		 sp = ct.getSharedPreferences("userconfig", Context.MODE_PRIVATE);
		 wifi = sp.getBoolean("wifi", false);
	}

	public class MyOnTouchListener implements OnTouchListener {

		private long satartCurrentTimeMillis;

		@Override
		public boolean onTouch(View arg0, MotionEvent arg1) {
			float currentX = arg1.getX();
			float currentY = arg1.getY();
			switch (arg1.getAction()) {
			case MotionEvent.ACTION_DOWN:
                satartCurrentTimeMillis = System.currentTimeMillis();
                handler.removeCallbacksAndMessages(null);
				break;

			case MotionEvent.ACTION_UP:
                 long duration = System.currentTimeMillis() - satartCurrentTimeMillis;
                 float upX = arg1.getX();
                 if(duration < 500 && upX == currentX){
                	 onTouchCllickCallBack.OnTouchCllick(currentItem);
                 }
                 startRoll();
			case MotionEvent.ACTION_CANCEL:
				 startRoll();
				break;
			case MotionEvent.ACTION_MOVE:
				 handler.removeCallbacksAndMessages(null);
				break;
			}
			return true;
		}

	}

	public boolean dispatchTouchEvent(MotionEvent ev) {
		final float x = ev.getX();
		final float y = ev.getY();
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			getParent().requestDisallowInterceptTouchEvent(true);
			mLastMotionX = x;
			mLastMotionY = y;
			break;
		case MotionEvent.ACTION_MOVE:
			if (Math.abs(x - mLastMotionX) < Math.abs(y - mLastMotionY)) {
				getParent().requestDisallowInterceptTouchEvent(false);
				LogUtils.d("in listview");
			} else {
				getParent().requestDisallowInterceptTouchEvent(true);
				LogUtils.d("in viewpager");
			}
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
			getParent().requestDisallowInterceptTouchEvent(false);
			break;
		}
		return super.dispatchTouchEvent(ev);
	}

	public class TaskPager implements Runnable {

		@Override
		public void run() {
			currentItem = (currentItem + 1) % imageUrlList.size();
			handler.obtainMessage().sendToTarget();
		}

	}

	public Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			RollViewPager.this.setCurrentItem(currentItem);
			startRoll();
		};
	};

	// 需要显示的文本内容
	private List<String> titleList;

	public void setTitle(TextView tvDescription, List<String> titleList) {
		// TODO Auto-generated method stub
		this.tvDescription = tvDescription;
		this.titleList = titleList;
		if (tvDescription != null && titleList != null && titleList.size() > 0) {
			tvDescription.setText(titleList.get(0));
		}
	}

	private List<String> imageUrlList;
	private ViewPagerAdatper adapter;
	private BitmapUtils bitmapUtils;
	private TaskPager taskPager;

	public void setImageUrl(List<String> imageUrlList) {
		// TODO Auto-generated method stub
		this.imageUrlList = imageUrlList;
	}

	public boolean hasSetAdapter = false;

	public void startRoll() {
		if (!hasSetAdapter) {
			hasSetAdapter = true;
			this.setOnPageChangeListener(new MyOnPageChangeListener());
			adapter = new ViewPagerAdatper();
			this.setAdapter(adapter);
		}
		handler.postDelayed(taskPager, 4000);
	}

	public int currentItem = 0;
	private MyOnTouchListener myOnTouchListener;
	private SharedPreferences sp;

	public class MyOnPageChangeListener implements OnPageChangeListener {
		int oldPositionItem = 0;

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPageSelected(int arg0) {
			// TODO Auto-generated method stub
			currentItem = arg0%titleList.size();
			if (tvDescription != null) {
				tvDescription.setText(titleList.get(arg0%titleList.size()));
			}
			if (dotList != null && dotList.size() > 0) {
				dotList.get(arg0%titleList.size()).setBackgroundResource(dotFocus);
				dotList.get(oldPositionItem%titleList.size()).setBackgroundResource(dotNormal);
			}
			oldPositionItem = arg0;
		}

	}

	public class ViewPagerAdatper extends PagerAdapter {

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			// TODO Auto-generated method stub
			((ViewPager) container).removeView((View) object);
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			ImageView iv = new ImageView(ct);
			iv.setScaleType(ScaleType.FIT_XY);
			wifi=true;
			if(wifi){
				int available = CommonUtil.isNetworkAvailable(ct);
				if(available==1){
					Picasso.with(ct).load(imageUrlList.get(position % dotList.size()))
					.placeholder(R.drawable.lunbo_loading).into(iv);
				}else{
					iv.setImageResource(R.drawable.lunbo_loading);
				}
			}else{
				Picasso.with(ct).load(imageUrlList.get(position % dotList.size()))
				.placeholder(R.drawable.lunbo_loading).into(iv);
			}
			iv.setOnTouchListener(myOnTouchListener);
			container.addView(iv);
			return iv;
		}

		@Override
		public int getCount() {
			return 100000;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

	}

	@Override
	protected void onDetachedFromWindow() {
		handler.removeCallbacksAndMessages(null);
		super.onDetachedFromWindow();
	}
}
